package com.jcompressor.maven;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;

import com.jcompressor.Jcompressor;
import com.jcompressor.entities.Project;

/**
 * @goal build
 * @phase package
 */
public class JcompressorMojo extends AbstractJcompressorMojo {
	
	@Override
	public void execute() throws MojoExecutionException, MojoFailureException {
		final Jcompressor jc = new Jcompressor();
		jc.extendProperties(this.buildMavenProperties());
		
		if (this.hasProjects()) {
			for (final String configuration : this.getProjects()) {
				jc.loadProject(configuration);
			}
		}
		else {
			if (StringUtils.isNotBlank(this.getProjectConfig())) {
				jc.loadProject(this.getProjectConfig());
			}
			else {
				jc.getStream().info("Configuration not provided");
			}
		}
		
		if (jc.getProjects().size() > 0) {
			jc.listProjects();
			for (final Project project : jc.getProjects()) {
				jc.initProject(project);
			}
		}
		
		jc.getStream().empty();
	}
	
	private Map<String, String> buildMavenProperties() {
		final Map<String, String> props = new HashMap<String, String>();
		props.put("projectName", this.getProjectName());
		props.put("projectArtifactId", this.getProjectArtifactId());
		props.put("projectVersion", this.getProjectVersion());
		props.put("projectBaseDirectory", this.getProjectBaseDirectory());
		props.put("projectBuildDirectory", this.getProjectBuildDirectory());
		return props;
	}
	
}